package jehc.djshi.oauth.client.util;

import cn.hutool.core.collection.CollectionUtil;
import jehc.djshi.common.base.BaseHttpSessionEntity;
import jehc.djshi.common.util.ExceptionUtil;
import jehc.djshi.common.util.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @Desc Token客户端存储
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Data
@Slf4j
@Component
public class OauthAttributesUtil {

    private Map<String,BaseHttpSessionEntity> attributes = new ConcurrentHashMap<>();

    /**
     * 存放Token对象
     * @param key
     * @param baseHttpSessionEntity
     * @return
     */
    public boolean put(String key,BaseHttpSessionEntity baseHttpSessionEntity){
        boolean result = true;
        if(StringUtil.isEmpty(key)){
            throw new ExceptionUtil("The key is empty in OauthHashUtil");
        }
        if(CollectionUtil.isEmpty(attributes)){
            attributes = new ConcurrentHashMap<>();
        }
        try {
            if(null != baseHttpSessionEntity){
                attributes.put(key,baseHttpSessionEntity);
            }
        }catch (Exception e){
            log.error("存放Token对象异常：{}",e);
            result = false;
        }
        return result;
    }

    /**
     * 删除Token
     * @param key
     * @return
     */
    public boolean remove(String key){
        boolean result = true;
        if(StringUtil.isEmpty(key)){
            throw new ExceptionUtil("The key is empty in OauthHashUtil");
        }
        try {
            attributes.remove(key);
        }catch (Exception e){
            log.error("移除Token对象异常：{}",e);
            result = false;
        }
       return result;
    }

    /**
     *
     * @param key
     * @return
     */
    public BaseHttpSessionEntity get(String key){
        if(StringUtil.isEmpty(key)){
            throw new ExceptionUtil("The key is empty in OauthHashUtil");
        }
        return attributes.get(key);
    }
}
